<template>
  <el-dialog v-model="visible" title="选择客户" width="70%" draggable>
    <div class="search-bar">
      <el-select
        v-model="currentCategory"
        placeholder="类别"
        style="width: 150px"
      >
        <el-option value="" label="全部类别" />
        <el-option
          v-for="category in allCategories"
          :key="category"
          :label="category"
          :value="category"
        />
      </el-select>

      <el-input
        v-model="searchKeyword"
        placeholder="输入编号/名称/联系人/电话查询"
        style="width: 300px; margin-left: 10px"
      />
      <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
        查询
      </el-button>
    </div>

    <el-table
      :data="filteredCustomers"
      style="width: 100%"
      border
      highlight-current-row
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'background-color': '#f5f7fa' }"
      ref="customerTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="CustomerType" label="类别" width="120" />
      <el-table-column prop="CustomerCode" label="客户编号" width="120" sortable />
      <el-table-column prop="CustomerName" label="客户名称" width="180" sortable />
      <el-table-column prop="ContactPerson" label="联系人" width="120" />
      <el-table-column prop="ContactPhone" label="联系电话" width="150" />
    </el-table>

    <div class="pagination" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        prev-text="上一页"
        next-text="下一页"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="selectAll">全选</el-button>
      <el-button @click="clearSelection">清空</el-button>
      <el-button
        type="primary"
        @click="confirmSelection"
        :disabled="selectedCustomers.length === 0"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, nextTick, defineExpose } from "vue";

const props = defineProps({
  customerList: {
    type: Array,
    required: true,
    default: () => [],
  },
});

const emit = defineEmits(["confirm"]);

// 状态管理
const visible = ref(false);
const currentCategory = ref("");
const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const customerTable = ref(null);
const selectedCustomers = ref([]);

// 打开对话框
const open = () => {
  visible.value = true;
  resetFilters();
  
  // 清空之前的选择
  nextTick(() => {
    if (customerTable.value) {
      customerTable.value.clearSelection();
    }
    selectedCustomers.value = [];
  });
};

// 获取所有类别
const allCategories = computed(() => {
  const categories = new Set();
  props.customerList.forEach((customer) => {
    if (customer.CustomerType) categories.add(customer.CustomerType);
  });
  return Array.from(categories);
});

// 过滤后的客户列表
const filteredCustomers = computed(() => {
  let result = [...props.customerList];

  // 类别过滤
  if (currentCategory.value) {
    result = result.filter((s) => s.CustomerType === currentCategory.value);
  }

  // 关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
      (s) =>
        (s.CustomerCode && s.CustomerCode.toLowerCase().includes(keyword)) ||
        (s.CustomerName && s.CustomerName.toLowerCase().includes(keyword)) ||
        (s.ContactPerson && s.ContactPerson.toLowerCase().includes(keyword)) ||
        (s.ContactPhone && s.ContactPhone.includes(keyword))
    );
  }

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  return result.slice(start, start + pageSize.value);
});

// 总记录数
const total = computed(() => {
  let result = [...props.customerList];

  if (currentCategory.value) {
    result = result.filter((s) => s.CustomerType === currentCategory.value);
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
      (s) =>
        (s.CustomerCode && s.CustomerCode.toLowerCase().includes(keyword)) ||
        (s.CustomerName && s.CustomerName.toLowerCase().includes(keyword)) ||
        (s.ContactPerson && s.ContactPerson.toLowerCase().includes(keyword)) ||
        (s.ContactPhone && s.ContactPhone.includes(keyword))
    );
  }

  return result.length;
});

// 行点击处理 - 点击行自动选择多选框
const handleRowClick = (row) => {
  // 切换当前行的选择状态
  customerTable.value.toggleRowSelection(row);
  
  // 更新选中的客户列表
  nextTick(() => {
    selectedCustomers.value = customerTable.value.getSelectionRows();
  });
};

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedCustomers.value = selection;
};

// 确认选择
const confirmSelection = () => {
  if (selectedCustomers.value.length > 0) {
    emit("confirm", selectedCustomers.value);
    visible.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  currentCategory.value = "";
  searchKeyword.value = "";
  currentPage.value = 1;
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  
  // 保持选中状态
  nextTick(() => {
    if (customerTable.value && selectedCustomers.value.length > 0) {
      const currentPageData = filteredCustomers.value;
      currentPageData.forEach(row => {
        const isSelected = selectedCustomers.value.some(
          s => s.CustomerCode === row.CustomerCode
        );
        if (isSelected) {
          customerTable.value.toggleRowSelection(row, true);
        }
      });
    }
  });
};

// 全选
const selectAll = () => {
  nextTick(() => {
    customerTable.value.toggleAllSelection();
    selectedCustomers.value = customerTable.value.getSelectionRows();
  });
};

// 清空选择
const clearSelection = () => {
  nextTick(() => {
    customerTable.value.clearSelection();
    selectedCustomers.value = [];
  });
};

// 暴露open方法给父组件
defineExpose({ open });
</script>

<style scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .el-table__header th) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__row.current-row) {
  background-color: #f0f7ff;
}

/* 确保选择框在点击行时可以被点击 */
:deep(.el-table__row .el-checkbox__input) {
  pointer-events: auto;
}
</style>